// pages/couponDetails/couponDetails.js
const couponService = require('../../../../api/couponService.js')
const wxbarcode = require('../../../../utils/self.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    coupon: {},
    type: '',
    loading: true,
    showCode: false,
    codeText: '',
    codeWidth: 586,
    codeHeight: 144,
  },
  getCouponDetails: function (activityId, id) {
    const that = this
    if (that.options.isExternal === 'false') {
      couponService.getById(activityId).then(res => {
        console.log(res)
        if (res) {
          let tempData = {
            ...res,
            rate: res.rate || res.rate === 0 ? (res.rate * 10).toFixed(1) : '',
          }
          if (that.data.type === 'assign') {
            if (res.startDate) {
              // let startTime = res.startDate.slice(0, 16)
              // let endTime = res.endDate.slice(0, 16)
              let startTime = res.startDate.split(' ')[0]
              let endTime = res.endDate.split(' ')[0]
              let effectiveTime = startTime + ' ~ ' + endTime
              let validityTime = startTime + ' —— ' + endTime
              let couponStatus = res.status
              tempData = {
                ...tempData,
                effectiveTime: effectiveTime,
                validityTime: validityTime,
                status: couponStatus
              }
            } else {
              tempData = {
                ...tempData,
                effectiveTime: '',
                validityTime: ''
              }
            }
            if (res.function === "FREESHIP") {
              tempData = {
                ...tempData,
                name: '运费券'
              }
            }
            that.setData({
              coupon: tempData,
              loading: false
            })
          } else {
            let id = that.options.couponId
            let postData = {
              cardNumEquals: id,
              pages: 1,
              pageSize: 10,
            }

            couponService.query(postData).then(res => {
              console.log(res)
              if (res.records.length > 0) {
                res.records.forEach(ele => {
                  if (ele.id === id) {
                    if (ele.bytimeStart) {
                      let startTime = ele.bytimeStart.slice(0, 16)
                      let endTime = ele.bytimeEnd.slice(0, 16)
                      let effectiveTime = startTime + ' ~ ' + endTime
                      let validityTime = startTime + ' —— ' + endTime
                      let couponStatus = ele.status
                      tempData = {
                        ...tempData,
                        effectiveTime: effectiveTime,
                        validityTime: validityTime,
                        status: couponStatus
                      }
                    } else {
                      tempData = {
                        ...tempData,
                        effectiveTime: '',
                        validityTime: ''
                      }
                    }
                  }
                });
                that.setData({
                  coupon: tempData,
                  loading: false
                })
              }
            }).catch(e => {
              wx.showToast({
                title: e.message,
                icon: 'none',
                duration: 2000
              })
              that.setData({
                loading: false
              })
            })
          }
        } else {
          that.setData({
            loading: false
          })
        }
      }).catch(e => {
        wx.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000
        })
        that.setData({
          loading: false
        })
      })
    } else {
      let couponData = JSON.parse(that.options.coupon)
      let tempData = {
        ...couponData,
        name: couponData.couponActivityName,
        useRule: couponData.remark,
        description: couponData.remark,
      }
      if (tempData.bytimeStart) {
        let startTime = tempData.bytimeStart.slice(0, 16)
        let endTime = tempData.bytimeEnd.slice(0, 16)
        let effectiveTime = startTime + ' ~ ' + endTime
        let validityTime = startTime + ' —— ' + endTime
        let couponStatus = tempData.status
        tempData = {
          ...tempData,
          effectiveTime: effectiveTime,
          validityTime: validityTime,
          status: couponStatus
        }
      } else {
        tempData = {
          ...tempData,
          effectiveTime: '',
          validityTime: ''
        }
      }
      if (tempData.status === 'OPEN' && tempData.externalCardNum) {
        that.showCode(tempData.externalCardNum)
      }
      that.setData({
        coupon: tempData,
        loading: false
      })
    }
  },
  showCode: function (codeText) {
    wxbarcode.barcode('barcode', codeText, this.data.codeWidth, this.data.codeHeight);
    this.setData({
      codeText: this.codeTextPartition(codeText),
      showCode: true
    })
  },
  codeTextPartition: function (val) {
    console.log(val)
    val = val.replace(/\s/g, '').replace(/(\w{4})(?=\w)/g, "$1 ");
    console.log(val)
    return val;
  },
  toAssign: function (val) {
    const that = this
    const couponId = that.data.coupon.id
    var currentCoupon = that.data.coupon
    if (currentCoupon.service === 'HD') {
      // 外部券 HD
      couponService.createCouponOrder(currentCoupon.dlyCouponActivityId).then(res => {
        console.log(res)
        if (res.status === 'ACQUIRE') {
          wx.showToast({
            title: '领券成功',
            icon: 'none',
            duration: 2000
          })
        } else if (res.status === 'CREATED') {
          let postData = {
            orderId: res.id,
            // payMethod: 'SWIFTPASS'
            payMethod: 'WX_MINI_APP'
          }
          couponService.getCouponPaySign(postData).then(res => {
            console.log(res)
            var resData = JSON.parse(res);
            var sign = JSON.parse(resData.sign)
            console.log(sign)
            if (postData.payMethod === 'WX_MINI_APP') {
              wx.requestPayment({
                'timeStamp': sign.timeStamp,
                'nonceStr': sign.nonceStr,
                'package': sign.packageValue,
                'signType': sign.signType,
                'paySign': sign.paySign,
                'success': function (res) {
                  wx.showToast({
                    title: '领券成功',
                    icon: 'none',
                    duration: 2000
                  })
                },
                'fail': function (res) {
                  console.log('支付失败')
                  console.log(res)
                  if (res.errMsg === 'requestPayment:fail cancel') {
                    wx.showToast({
                      title: '您取消了支付~',
                      icon: 'none',
                      duration: 2000
                    })
                  } else {
                    wx.showToast({
                      title: res.errMsg,
                      icon: 'none',
                      duration: 2000
                    })
                  }
                }
              })
            } else if (postData.payMethod === 'SWIFTPASS') {
              wx.requestPayment({
                'timeStamp': sign.timeStamp,
                'nonceStr': sign.nonceStr,
                'package': sign.package,
                'signType': sign.signType,
                'paySign': sign.paySign,
                'success': function (res) {
                  wx.showToast({
                    title: '领券成功',
                    icon: 'none',
                    duration: 2000
                  })
                },
                'fail': function (res) {
                  console.log('支付失败')
                  console.log(res)
                  if (res.errMsg === 'requestPayment:fail cancel') {
                    wx.showToast({
                      title: '您取消了支付~',
                      icon: 'none',
                      duration: 2000
                    })
                  } else {
                    wx.showToast({
                      title: res.errMsg,
                      icon: 'none',
                      duration: 2000
                    })
                  }
                }
              })
            }

          }).catch(err => {
            if (err.code === 1) {
              wx.showToast({
                title: '领券失败',
                icon: 'none',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            }
          })
        } else {
          wx.showToast({
            title: res.acquireFailedReason,
            icon: 'none',
            duration: 2000
          })
        }
      }).catch(e => {
        console.log(e)
        wx.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000
        })
      })
    } else {
      // 内部券
      if (currentCoupon.balance > 0) {
        let postData = {
          activityId: couponId
        }
        couponService.assign(postData).then(res => {
          console.log(res)
          wx.showToast({
            title: '领券成功',
            icon: 'none',
            duration: 2000
          })
        }).catch(e => {
          console.log(e)
          if (e.code === 17005) {
            wx.showToast({
              title: '券活动指定的有效期已经过期，不能领取~',
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: e.message,
              icon: 'none',
              duration: 2000
            })
          }
        })
      } else {
        wx.showToast({
          title: '券已经被抢光了哦~',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },
  // 去购物
  toIndex: function () {
    wx.switchTab({
      url: '../../index/index/index'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    console.log(options)
    this.getCouponDetails(options.couponActivityId, options.couponId)
    if (options.type === 'freeship') {
      wx.setNavigationBarTitle({
        title: '运费优惠券'
      })
    }
    this.setData({
      type: options.type,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})